/*
 * @Author: LF
 * @Description: 版头
 * @Date: 2020-10-21 08:38:38
 * @LastEditTime: 2020-10-24 10:28:42
 */
import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import jwt from 'jsonwebtoken'
// 引入菜单，下拉框和ICON组件
import { Menu, Dropdown, Icon, message, Badge, Avatar } from 'antd'
import { getClassify } from '@/services/topic'
import { getUserData } from '@/services/user'
import { getWebStyle } from '@/services/style'

export default class top extends Component {
  constructor(props) {
    super(props)

    this.state = {
      userData: {},
      web_title: '望潮论坛',
      classify: [],
      flag: false
    }
  }

  // 页面挂载后判断：如果浏览器中存在token，则表明用户已登录，需要向服务器请求用户数据
  async componentDidMount() {
    if (sessionStorage.getItem('token')) {
      let { data: res } = await getUserData()
      if (res && res.ok === 1) {
        this.setState({
          userData: res.data
        })
      } else {
        message.error(res.msg)
      }
    }
    // 请求网页标题数据
    this.getWebTitle()
    // 请求所有频道
    this.getAllClassify()
  }
  // 请求所有频道
  getAllClassify = async () => {
    let { data: res } = await getClassify()
    if (res && res.ok === 1) {
      let arr = [
        {
          id: '',
          name: '推荐'
        }
      ]
      arr = arr.concat(res.result)
      this.setState({
        classify: arr
      })
    }
  }
  // 请求网页标题数据
  getWebTitle = async () => {
    let { data: res } = await getWebStyle()
    if (res && res.ok === 1) {
      this.setState({
        web_title: res.data.web_title
      })
      document.body.style.backgroundColor = res.data.web_color || '#e2e2e2'
    }
  }

  // 展开/收起下拉列表
  changeStyle = () => {
    if (!this.state.flag) {
      this.unfoldList()
    } else {
      this.shrinkList()
    }
    this.setState({
      flag: !this.state.flag
    })
  }

  // 展开列表
  unfoldList = () => {
    let lines = document.querySelectorAll('.line')
    let list = document.querySelector('.list')
    lines[0].style.transform = 'rotate(45deg)'
    lines[0].style.top = '44%'
    lines[1].style.display = 'none'
    lines[2].style.transform = 'rotate(-45deg)'
    lines[2].style.top = '-48%'
    list.style.maxHeight = 1000 + 'px'
  }

  // 收起列表
  shrinkList = () => {
    let lines = document.querySelectorAll('.line')
    let list = document.querySelector('.list')
    lines[0].style.transform = lines[2].style.transform = 'none'
    lines[0].style.top = lines[2].style.top = 0
    lines[1].style.display = 'block'
    list.style.maxHeight = 0
  }

  // 发布新话题
  publish = () => {
    if (sessionStorage.getItem('token')) {
      window.location.href = '/publish'
    } else {
      message.error('登录后才能发布新话题哦')
    }
  }

  // 登出
  logout = () => {
    sessionStorage.clear()
    window.location.href = '/'
  }

  // 切换板块
  changePlate = (item) => {
    this.changeStyle()
    window.location.href = '/' + item.id
  }

  render() {
    const { web_title, userData } = this.state
    const menuItem = [
      {
        src: '/myPublish',
        title: '我发布的'
      },
      {
        src: '/myComment',
        title: '我参与的'
      },
      {
        src: '/myMessage',
        title: '我的消息'
      },
      {
        src: '/personalCenter',
        title: '个人中心'
      },
      {
        src: null,
        title: '退出登录',
        onclick: this.logout
      }
    ]
    const menu = (
      <Menu>
        {menuItem.map((item, index) => {
          return (
            <Menu.Item key={index} onClick={item.onclick ? item.onclick : null}>
              {item.src && <Link to={item.src}>{item.title}</Link>}
              {!item.src && item.title}
            </Menu.Item>
          )
        })}
      </Menu>
    )
    const classifyList = []
    this.state.classify.forEach((item, index) => {
      classifyList.push(
        <li key={index} onClick={() => this.changePlate(item)}>
          {item.name}
        </li>
      )
    })
    return (
      <div className="navTop">
        <div className="container">
          <a id="logo" href="/">
            <img src={require('../static/images/logo.png')} />
            <span>{web_title || '望潮论坛'}</span>
          </a>
          <div className="collapse">
            <ul>{classifyList}</ul>
          </div>
          <div className="user-operation">
            <div onClick={this.publish} className="publish-news apple-font">
              发布新话题
            </div>
            <ul style={{ marginLeft: '10px' }}>
              {sessionStorage.getItem('token') ? (
                <Dropdown overlay={menu} trigger={['click']}>
                  <li style={{ display: 'flex', alignItems: 'center' }}>
                    <Avatar size={30} icon="user" src={userData.avatar} />
                    <span style={{ marginLeft: 5 }}>
                      {jwt.decode(sessionStorage.getItem('token')).username}
                    </span>
                    <Icon style={{ marginLeft: 5 }} type="caret-down" />
                  </li>
                </Dropdown>
              ) : (
                <>
                  <li>
                    <a href="/register">注册</a>
                  </li>
                  <li>
                    <a href="/login">登录</a>
                  </li>
                </>
              )}
            </ul>
          </div>
          <div className="mobile-area">
            <div className="button" onClick={this.changeStyle}>
              <div className="line line1"></div>
              <div className="line line2"></div>
              <div className="line line3"></div>
            </div>
            <div className="list">
              <ul>{classifyList}</ul>
              <div className="user-operation">
                <div onClick={this.publish} className="publish-news apple-font">
                  发布新话题
                </div>
                <ul style={{ margin: '10px 0px' }}>
                  {!sessionStorage.getItem('token') && (
                    <>
                      <li>
                        <a href="/register">注册</a>
                      </li>
                      <li>
                        <a href="/login">登录</a>
                      </li>
                    </>
                  )}
                </ul>
              </div>
            </div>
          </div>
        </div>
      </div>
    )
  }
}
